package cn.yomigaeri.signal.service.impl;

import cn.yomigaeri.common.entity.dto.SignalDTO;
import cn.yomigaeri.common.entity.po.Rule;
import cn.yomigaeri.signal.client.WarnClient;
import cn.yomigaeri.signal.producer.SignalProducer;
import cn.yomigaeri.signal.service.UploadSignalService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: UploadSignalServiceImpl
 * @Package: cn.yomigaeri.signal.service.impl
 * @Description:
 * @Author Yomigaeri
 * @Create 2025/6/4 16:14
 * @Version 1.0
 */
@Service
@RequiredArgsConstructor
public class UploadSignalServiceImpl implements UploadSignalService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final SignalProducer signalProducer;
    private final WarnClient warnClient;

    @Override
    public void uploadAndSave(SignalDTO signalDTO) {
        signalDTO.setCreateTime(LocalDateTime.now());
        String key = "SignalOfCarId:" + signalDTO.getCarId().toString() + ":";
        //保存进入redis中
        if (signalDTO.getWarnId() == null) {
            Set<Integer> warnIds = warnClient.getRules().stream().map(Rule::getWarnId).collect(Collectors.toSet());
            for (Integer warnId : warnIds) {
                signalDTO.setWarnId(warnId);
                redisTemplate.opsForValue().set(key + warnId, signalDTO);
            }
            signalDTO.setWarnId(null);
        } else {
            redisTemplate.opsForValue().set(key + signalDTO.getWarnId(), signalDTO);
        }

        //异步存入数据库
        signalProducer.sendSaveMessage(signalDTO);
    }
}
